<?php
/**
 * Form 表单服务层
 * @author maniac
 */
namespace app\common\service;



use app\common\model\Fields as FieldsModel;
use app\common\service\Fields as FieldsService;
use app\facade\Regions;
use app\facade\Categories;

class Forms extends Base
{
    /**
     * 获取 form 表单
     * @param string $dbname      数据表名称
     * @param int    $form_id     form 模型 id
     * @param int    $id          数据主键
     * @param string $type        录入项状态，'q' => qenter, 'h' => henter, '' => enter
     */
    public function forms($dbname, $form_id, $id, $type = '')
    {
        // 获取字段所属表对应 form 模型表及主表
        $map = config('db_map.');
        if (isset($map[$dbname])) {
            // form 表单模型
            $model     = 'app\common\model\\' . $map[$dbname]['form'];
            // 主数据表模型
            $mainModel = isset($map[$dbname]['main_model']) ? $map[$dbname]['main_model'] : '';
            $mainModel = $mainModel ? 'app\common\model\\'.$mainModel : '';
            // 当前数据表模型
            $currentModel = 'app\common\model\\'.parse_table_name($dbname);
            $currentModel = new $currentModel;
        } else {
            // 系统模型模型
            $model     = 'app\common\model\Mods';
            // 主数据表模型
            $mainModel = 'app\common\model\Contents';
            // 当前数据表模型
            $currentModel = \think\Db::name($dbname);
            $dbname = 'contents,'.$dbname;
        }
        if ($mainModel) {
            // 主表数据
            $mainData = $mainModel::field(true)->where('id', $id)->find();
            // 副表数据
            $fData    = $currentModel->field(true)->where('id', $id)->find();
            $mainData = $mainData ? $mainData->toArray() : [];
            $fData    = $fData ?: [];
            if (is_object($fData)) $fData = $fData->toArray();
            // 合并主副表数据
            if (is_array($mainData) && is_array($fData)) {
                $info = array_merge($mainData, $fData);
            }
        } else {
            // 信息数据
            $info = $currentModel->field(true)->where('id', $id)->find();
        }
        // 要查询的字段
        $field = 'field,'.$type.'enter,'.$type.'must_enter';
        // 获取 from 表单数据
        $form  = $model::field($field)->where('id', $form_id)->find();
        // 字段名称
        $field = $form['field'];
        // 录入项
        $enter = $form[$type.'enter'];
        $mustEnter = $form[$type.'must_enter'];
        return $this->generateHtml($dbname, $info, $enter, $mustEnter, $field);
    }
    //地区三级联动
    public function area($dbname, $info, $enter, $mustEnter, $field)

    {

        return $this->generateHtmls($dbname, $info, $enter, $mustEnter, $field);

    }


    
    /**
     * 生成 from html
     * @param  string $dbname 数据表名称
     * @param  array  $info   信息数据
     * @param  array  $enter  录入项
     * @param  array  $field  字段名称
     */
    private function generateHtml($dbname, $info, $enter, $mustEnter, $field)
    {

        $fields = FieldsModel::field('id,f,ftype,fform,fvalue')->where('tbname', 'in', $dbname)->order('id ASC')->select();

        $fields = $fields ? $fields->toArray() : [];

        if ($fields) {
            $data   = [];
            foreach ($fields as $k => $v) {
                $data[$v['id']] = $v;
            }
            $html = [];

            foreach ($enter as $v) {

                $label = '';

                switch ($data[$v]['fform']) {

                    case 'text': case 'password': case 'textarea': case 'editor':

                        $label = ' for="'.$data[$v]['f'].'"';

                        break;

                }

                $ret['label']   = '<label'.$label.'>'.$field[$v].(in_array($v, $mustEnter) ? '<em>*</em>' : '').'</label>';

                $ret['name']    = $data[$v]['f'];

                $ret['type']    = $data[$v]['fform'];



                switch ($data[$v]['fform']) {

                    // 文本框/密码框

                    case 'text': case 'password':

                        $ret['value'] = '<input type="'.$data[$v]['fform'].'" class="u-ipt u-ipt-long" name="'.$data[$v]['f'].'" id="'.$data[$v]['f'].'" placeholder="请输入'.$field[$v].'" value="'.(isset($info[$data[$v]['f']]) ? $info[$data[$v]['f']] : $data[$v]['fvalue']).'" />';

                        break;

                    // 日期选择

                    case 'timestamp(Y-m-d)': case 'timestamp(Y-m-d H:i:s)':

                        if ($data[$v]['fform'] == 'timestamp(Y-m-d)') {

                            $timeFmt = 'Y-m-d';

                            $dateFmt = "{dateFmt:'yyyy-MM-dd'}";

                        } elseif ($data[$v]['fform'] == 'timestamp(Y-m-d H:i:s)') {

                            $timeFmt = 'Y-m-d H:i:s';

                            $dateFmt = "{dateFmt:'yyyy-MM-dd HH:mm:ss'}";

                        }

                        if ($data[$v]['f'] == 'post_time') {

                            $data[$v]['fvalue'] = date('Y-m-d H:i:s', time());

                        }

                        $ret['value'] = '<input type="text" class="u-ipt u-ipt-long" name="'.$data[$v]['f'].'" id="'.$data[$v]['f'].'" placeholder="请选择'.$field[$v].'" onclick="WdatePicker('.$dateFmt.')" value="'.(isset($info[$data[$v]['f']]) && $info[$data[$v]['f']] && $data[$v]['f'] != 'post_time' ? date($timeFmt, $info[$data[$v]['f']]) : $data[$v]['fvalue']).'" readonly />';

                        break;

                    // case 穿透，拆分字段值为数组

                    case 'select': case 'radio': case 'checkbox':

                        $option = [];

                        $temp   = explode("\r\n", $data[$v]['fvalue']);

                        foreach ($temp as $item) {

                            if (strpos($item, '==') !== false) {

                                $arr     = explode('==', $item);

                                $arrx    = explode(':default', $arr[1]);

                                $default = count($arrx) > 1 ? 1 : 0;

                                if (isset($info[$data[$v]['f']]) && $info[$data[$v]['f']] == $arr[0]) {

                                    $default = 1;

                                }

                                $option[] = [

                                    'value'   => $arr[0],

                                    'text'    => $arrx[0],

                                    'default' => $default,

                                ];

                            } else {

                                $arr = explode(':default', $item);

                                $default = count($arr) > 1 ? 1 : 0;

                                if (isset($info[$data[$v]['f']]) && $info[$data[$v]['f']] == $arr[0]) {

                                    $default = 1;

                                }

                                $option[] = [

                                    'value'   => $arr[0],

                                    'text'    => $arr[0],

                                    'default' => $default,

                                ];

                            }

                        }

                        $ret['value'] = '';

                        if ($data[$v]['fform'] == 'select') {

                            $ret['value'] = '<div class="lay-select"><select name="'.$data[$v]['f'].'">';

                            foreach ($option as $val) {

                                if (isset($info[$data[$v]['f']]) && $info[$data[$v]['f']]) {

                                    $selected = $val['value'] == $info[$data[$v]['f']] ? ' selected' : '';

                                } else {

                                    $selected = $val['default'] ? ' selected' : '';

                                }

                                $ret['value'] .= '<option value="'.$val['value'].'"'.$selected.'>'.$val['text'].'</option>';

                            }

                            $ret['value'] .= '</select></div>';

                        } elseif ($data[$v]['fform'] == 'radio') {

                            foreach ($option as $val) {

                                if (isset($info[$data[$v]['f']]) && $info[$data[$v]['f']]) {

                                    $checked = $val['value'] == $info[$data[$v]['f']] ? ' checked' : '';

                                } else {

                                    $checked = $val['default'] ? ' checked' : '';

                                }

                                $ret['value'] .= '<input type="radio" name="'.$data[$v]['f'].'" value="'.$val['value'].'" title="'.$val['text'].'"'.$checked.' />';

                            }

                        } elseif ($data[$v]['fform'] == 'checkbox') {

                            $ret['value'] = '<div class="lay-checked">';

                            foreach ($option as $val) {

                                if (isset($info[$data[$v]['f']]) && $info[$data[$v]['f']]) {

                                    $checked = '';

                                    if (strpos(','.$info[$data[$v]['f']].',', ','.$val['value'].',') !== false) {

                                        $checked = ' checked';

                                    }

                                } else {

                                    $checked = $val['default'] ? ' checked' : '';

                                }

                                $ret['value'] .= '<input type="checkbox" name="'.$data[$v]['f'].'[]" value="'.$val['value'].'" title="'.$val['text'].'" lay-skin="primary"'.$checked.' />';

                            }

                            $ret['value'] .= '</div>';

                        }

                        break;

                    // 多行文本框

                    case 'textarea':

                        $ret['value'] = '<div class="m-textarea"><textarea name="'.$data[$v]['f'].'" class="u-tarea" id="'.$data[$v]['f'].'" placeholder="请输入'.$field[$v].'">'.(isset($info[$data[$v]['f']]) ? $info[$data[$v]['f']] : $data[$v]['fvalue']).'</textarea></div>';

                        break;

                    // 编辑器

                    case 'editor':

                        $uploadUri = url("api/v1/upload", ["path" => session("userid", "", session_prefix()), "type" => "pic", "module" => request()->module() ?: "addons"]);

                        $fileManageUri = url("api/v1/fileManager", ["path" => session("userid", "", session_prefix()), "type" => "pic", "module" => request()->module() ?: "addons"]);

                        $ret['value'] = '<textarea name="'.$data[$v]['f'].'" id="'.$data[$v]['f'].'" style="width:100%;height:300px !important;">'.(isset($info[$data[$v]['f']]) ? $info[$data[$v]['f']] : $data[$v]['fvalue']).'</textarea>';

                        break;

                    // 上传单图

                    case 'image':

                        $str = isset($info[$data[$v]['f']]) ? attach_html($info[$data[$v]['f']], $data[$v]['f']) : '';

                        $ret['value'] = '<button type="button" class="layui-btn u-upload-pic" data-name="'.$data[$v]['f'].'"><i class="layui-icon">&#xe67c;</i>上传图片</button><div class="m-pic"><ul>'.$str.'</ul></div>';

                        break;

                    // 上传附件

                    case 'file':

                        $str = isset($info[$data[$v]['f']]) ? attach_html(unserialize($info[$data[$v]['f']]), $data[$v]['f'], 'file') : '';

                        $ret['value'] = '<button type="button" class="layui-btn u-upload-file" data-name="'.$data[$v]['f'].'"><i class="layui-icon">&#xe67c;</i>上传附件</button><div class="m-files"><ul class="m-jquery-sorted">'.$str.'</ul></div>';

                        break;

                    // 上传多图

                    case 'photos':

                        $str = isset($info[$data[$v]['f']]) ? attach_html(unserialize($info[$data[$v]['f']]), $data[$v]['f'], 'pics') : '';

                        $ret['value'] = '<button type="button" class="layui-btn u-upload-pics" data-name="'.$data[$v]['f'].'"><i class="layui-icon">&#xe67c;</i>上传图片</button><div class="m-pics"><ul class="m-jquery-sorted clearfix">'.$str.'</ul></div>';

                        break;
                }

                $html[] = $ret;

            }

            return $html;

        }

        return '';

    }


    /**
     * 生成 from html
     * @param  string $dbname 数据表名称
     * @param  array  $info   信息数据
     * @param  array  $enter  录入项
     * @param  array  $field  字段名称
     */
    public static function generateHtmls($dbname, $info, $enter, $mustEnter, $field,$where = 'tbname')
    {

        $fields = FieldsService::rowss([[$where, 'in', $dbname]], 'id,f,ftype,fform,fvalue');

        $fields = $fields ? $fields->toArray() : [];
        if ($fields) {
            $data   = [];
            foreach ($fields as $k => $v) {
                $data[$v['id']] = $v;
            }
            $html = [];

            foreach ($enter as $v) {
                $label = '';
                switch ($data[$v]['fform']) {
                    case 'text': case 'password': case 'textarea': case 'editor':
                    $label = ' for="'.$data[$v]['f'].'"';
                    break;
                }
                $ret['label']    = '<label'.$label.'>'.$field[$v].(in_array($v, $mustEnter) ? '<em>*</em>' : '').'</label>';
                $ret['name']     = $data[$v]['f'];
                $ret['fname']    = $field[$v];
                $ret['type']     = $data[$v]['fform'];
                $ret['required'] = in_array($v, $mustEnter) ? 1 : 0;

                switch ($data[$v]['fform']) {
                    // 地区三级联动
                    case 'area_linkage':
                        $province = Regions::regions();
                        $city     = [];
                        if ($info && $info['province']) {
                            $city = Regions::regions($info['province']);
                        }
                        $district = [];
                        if ($info && $info['province'] && $info['city']) {
                            $district = Regions::regions($info['province'], $info['city']);
                        }
                        $provinceStr = '<option value="0">请选择省份</option>';
                        if (!empty($province)) {
                            foreach ($province as $v) {
                                $selected     = '';
                                if ($info && $info['province'] && $v['id'] == $info['province']) $selected = ' selected';
                                $provinceStr .= '<option value="'.$v['id'].'"'.$selected.'>'.$v['name'].'</option>';
                            }
                        }
                        $cityStr = '<option value="0">请选择城市</option>';
                        if (!empty($city)) {
                            foreach ($city as $v) {
                                $selected     = '';
                                if ($info && $info['city'] && $v['id'] == $info['city']) $selected = ' selected';
                                $cityStr .= '<option value="'.$v['id'].'"'.$selected.'>'.$v['name'].'</option>';
                            }
                        }
                        $districtStr = '<option value="0">请选择区域</option>';
                        if (!empty($district)) {
                            foreach ($district as $v) {
                                $selected     = '';
                                if ($info && $info['district'] && $v['id'] == $info['district']) $selected = ' selected';
                                $districtStr .= '<option value="'.$v['id'].'"'.$selected.'>'.$v['name'].'</option>';
                            }
                        }

                        $ret['value'] = '<div class="lay-select m-linkage"><select name="province" id="province" lay-filter="province">'.$provinceStr.'</select></div><div class="lay-select m-linkage"><select name="city" id="city" lay-filter="city">'.$cityStr.'</select></div><div class="lay-select m-linkage"><select name="district" id="district" lay-filter="district">'.$districtStr.'</select></div>';
                        break;
                    // 广告位置
                    case 'place_linkage':
                        $category_id = Categories::categories();
                        $category_id1     = [];
                        if ($info && $info['category_id']) {
                            $category_id1 = Categories::categories($info['category_id']);
                        }
                        $category_id2 = [];
                        if ($info && $info['category_id'] && $info['category_id1']) {
                            $category_id2 = Categories::categories($info['category_id'], $info['category_id1']);
                        }
                        $provinceStr = '<option value="0">请选择分类</option>';
                        if (!empty($category_id)) {
                            foreach ($category_id as $v) {
                                $selected     = '';
                                if ($info && $info['category_id'] && $v['id'] == $info['category_id']) $selected = ' selected';
                                $provinceStr .= '<option value="'.$v['id'].'"'.$selected.'>'.$v['name'].'</option>';
                            }
                        }
                        $cityStr = '<option value="0">请选择1级位置</option>';
                        if (!empty($category_id1)) {
                            foreach ($category_id1 as $v) {
                                $selected     = '';
                                if ($info && $info['category_id1'] && $v['id'] == $info['category_id1']) $selected = ' selected';
                                $cityStr .= '<option value="'.$v['id'].'"'.$selected.'>'.$v['name'].'</option>';
                            }
                        }
                        $districtStr = '<option value="0">请选择2级位置</option>';
                        if (!empty($category_id2)) {
                            foreach ($category_id2 as $v) {
                                $selected     = '';
                                if ($info && $info['category_id2'] && $v['id'] == $info['category_id2']) $selected = ' selected';
                                $districtStr .= '<option value="'.$v['id'].'"'.$selected.'>'.$v['name'].'</option>';
                            }
                        }
                        $ret['value'] = '<div class="lay-select m-linkage"><select name="category_id" id="category_id" lay-filter="category_id">'.$provinceStr.'</select></div><div class="lay-select m-linkage"><select name="category_id1" id="category_id1" lay-filter="category_id1">'.$cityStr.'</select></div><div class="lay-select m-linkage"><select name="category_id2" id="category_id2" lay-filter="category_id2">'.$districtStr.'</select></div>';
                        break;
                }
                $html[] = $ret;
            }
            return $html;
        }
        return '';
    }
    public static function getProvinceCityDistrictSelect($province_id="province", $city_id="city",$district_id="district",$province_value="",$city_value="",$district_value="",$sort=1){
    	$province = Regions::regions();
    	$city     = [];
    	if ($province_value) {
    		$city = Regions::regions($province_value);
    	}
    	$district = [];
    	if ($province_value && $city_value) {
    		$district = Regions::regions($province_value, $city_value);
    	}
    	$provinceStr = '<option value="0">请选择省份</option>';
    	if (!empty($province)) {
    		foreach ($province as $v) {
    			$selected     = '';
    			if ($v['id'] == $province_value) $selected = ' selected';
    			$provinceStr .= '<option value="'.$v['id'].'"'.$selected.'>'.$v['name'].'</option>';
    		}
    	}
    	$cityStr = '<option value="0">请选择城市</option>';
    	if (!empty($city)) {
    		foreach ($city as $v) {
    			$selected     = '';
    			if ($v['id'] == $city_value) $selected = ' selected';
    			$cityStr .= '<option value="'.$v['id'].'"'.$selected.'>'.$v['name'].'</option>';
    		}
    	}
    	$districtStr = '<option value="0">请选择区域</option>';
    	if (!empty($district)) {
    		foreach ($district as $v) {
    			$selected     = '';
    			if ($v['id'] == $district_value) $selected = ' selected';
    			$districtStr .= '<option value="'.$v['id'].'"'.$selected.'>'.$v['name'].'</option>';
    		}
    	}
    	if($sort == 1){
     		$html = '<div class="lay-select m-linkage"><select name="'.$province_id.'" id="province" lay-filter="'.$province_id.'">'.$provinceStr.'</select></div>'
					.'<div class="lay-select m-linkage"><select name="'.$city_id.'" id="city" lay-filter="'.$city_id.'">'.$cityStr.'</select></div>'
					.'<div class="lay-select m-linkage"><select name="'.$district_id.'" id="district" lay-filter="'.$district_id.'">'.$districtStr.'</select></div>';
    	}else{
    		$html = '<div class="lay-select m-linkage"><select name="'.$province_id.'" id="province" lay-filter="'.$province_id.'">'.$provinceStr.'</select></div>'
    				.'<div class="lay-select m-linkage"><select name="'.$city_id.'" id="city" lay-filter="'.$city_id.'">'.$cityStr.'</select></div>';
    	}
    	return $html;
    }
}
